<template>
  <div>
    <!-- This is lesson page -->

    <!-- breadcrumb nav -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/manager' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>课程管理</el-breadcrumb-item>
      <el-breadcrumb-item>排课记录</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 查找排课：搜索框 -->
    <el-card class="search-bar">
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="2" :offset="0">
          精准查找
        </el-col>
        <el-col :span="10" :offset="0">
          <el-input
          placeholder="请输入内容"
          v-model="searchValue"
          class="input-with-select"
          clearable>
            <el-select v-model="searchMethod" slot="prepend" placeholder="课程名称">
              <el-option label="教师名称" value="1"></el-option>
              <el-option label="课程名称" value="2"></el-option>
              <el-option label="班级名称" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchLesson()"></el-button>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 排课列表 -->
    <el-card class="lesson-list">
      <el-button type="success" plain @click="MultiLessonDelete">删除</el-button>

      <!-- 所有的列表信息 -->
      <el-table
      :data="lessonTable"
      class="lesson-table"
      style="width: 100%">
        <el-table-column
          type="selection"
          width="50">
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          align="center"
          prop="create_time"
          width="">
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column
          label="更新时间"
          align="center"
          prop="update_time"
          width="">
        </el-table-column>
        <!-- 课程名 -->
        <el-table-column
          label="课程名称"
          align="center"
          prop="course_name"
          width="">
        </el-table-column>
        <!-- 专业 -->
        <el-table-column
          prop="class_name"
          align="center"
          label="上课专业">
        </el-table-column>
        <!-- 教师名称 -->
        <el-table-column
          prop="teacher_name"
          align="center"
          label="上课教师">
        </el-table-column>
        <!-- 上课从第几周到第几周 -->
        <el-table-column
          prop="class_cycle"
          align="center"
          label="上课周期">
        </el-table-column>
        <!-- 上课时间 -->
        <el-table-column
          prop="time_list[0].courseTime"
          align="center"
          label="上课时间">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                显示时间<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item, index) in scope.row.time_list" :key="index">{{ item.courseTime }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="课程状态"
          width="260">
          <template slot-scope="scope">
            <el-radio-group
              v-model="scope.row.course_teacher_state"
              @change="changeCourseStatus(scope.row.id, scope.row.course_teacher_state)"
              size="mini">
              <el-radio-button :label="0">选课阶段</el-radio-button>
              <el-radio-button :label="1">上课阶段</el-radio-button>
              <el-radio-button :label="2">结课阶段</el-radio-button>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column
          width="180"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="editLesson(scope.row)">编辑</el-button>
            <el-button type="danger" plain size="mini" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页导航 -->
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="totalLesson">
      </el-pagination>
    </el-card>

    <!-- 删除课程的确认弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>确认删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteLesson()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改排课的表单抽屉 -->
    <el-drawer
      class="add-lesson"
      :title="currentLesson.class_name"
      size="45%"
      :visible.sync="editLessonDrawer"
      :direction="drawerDirection"
      :before-close="handleClose">
      <el-form
        :model="currentLesson"
        :rules="editLessonRules"
        ref="editLessonForm">
        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <el-form-item
              label="上课教师："
              prop="teacher_name">
              <el-select size="small" v-model="currentLesson.teacher_name" placeholder="请选择">
                <el-option
                  v-for="item in teacherList"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- <i>*</i>
            排课编号： -->
            <el-form-item
              label="排课编号："
              prop="course_teacher_num">
              <el-input
                size="small"
                v-model.number="currentLesson.course_teacher_num">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" v-for="(time, index) in editTimeList" :key="index">
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;上课时间： -->
            <el-form-item
              label="上课时间："
              :rules="[
                { required: 'true', message: '请选择上课时间', trigger: 'change' }
              ]">
              <el-select v-model="time.week" placeholder="请选择星期" size="small">
                <el-option label="" value="周一"></el-option>
                <el-option label="" value="周二"></el-option>
                <el-option label="" value="周三"></el-option>
                <el-option label="" value="周四"></el-option>
                <el-option label="" value="周五"></el-option>
                <el-option label="" value="周六"></el-option>
                <el-option label="" value="周日"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item
              label=""
              :rules="[
              { required: 'true', message: '请选择上课节次', trigger: 'change' }
              ]">
              <el-select v-model="time.section" placeholder="请选择节次" size="small">
                <el-option label="" value="1-2节"></el-option>
                <el-option label="" value="3-4节"></el-option>
                <el-option label="" value="5-6节"></el-option>
                <el-option label="" value="7-8节"></el-option>
                <el-option label="" value="9-10节"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <i class="el-icon-circle-plus" @click="addTimeValues"></i>
          </el-col>
          <el-col :span="2">
            <i class="el-icon-remove" @click="removeAddTime(time,index)"></i>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;上课专业： -->
            <el-form-item
              label="上课专业："
              prop="class_name">
              <el-select v-model="currentLesson.class_name" placeholder="请选择班级" size="small">
                <el-option label="" value="软件工程"></el-option>
                <el-option label="" value="计算机科学与技术"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;上课教室： -->
            <el-form-item
              label="上课教室："
              prop="classroom">
              <el-input
                size="small"
                v-model="currentLesson.classroom">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;课程分类： -->
            <el-form-item
              label="课程分类："
              prop="genre">
              <el-select v-model="currentLesson.genre" placeholder="请选择类型" size="small">
                <el-option label="" value="必修课"></el-option>
                <el-option label="" value="选修课"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;时间分类： -->
            <el-form-item
              label="时间分类："
              prop="time_type">
              <el-select v-model="currentLesson.time_type" placeholder="请选择类型" size="small">
                <el-option label="每周都有" value="0"></el-option>
                <el-option label="单周" value="1"></el-option>
                <el-option label="双周" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;实际课时： -->
            <el-form-item
              label="实际课时："
              prop="class_period">
              <el-input
                size="small"
                v-model.number="currentLesson.class_period">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;实际学分： -->
            <el-form-item
              label="实际学分："
              prop="credict">
              <el-input
                size="small"
                v-model="currentLesson.credict">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;上课周期： -->
            <el-form-item
              label="上课周期："
              prop="week_start">
              <el-select size="small" v-model="currentLesson.week_start" placeholder="开始">
                <el-option
                  v-for="item in weekStart"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label=""
              prop="week_end">
              至&nbsp;&nbsp;&nbsp;&nbsp;
              <el-select size="small" v-model="currentLesson.week_end" placeholder="结束">
                <el-option
                  v-for="item in weekEnd"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              &nbsp;&nbsp;周
            </el-form-item>
          </el-col>
        </el-row>

        <el-button type="school" class="submit" size="small" @click="editLessonSubmit()">提交</el-button>
        <el-button type="success" size="small" plain @click="editLessonDrawer = false">取消</el-button>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { toDateString } from '@/utils/time.js'
import { getAllMajors, getAllTeachers } from '@/utils/dropdown.js'
export default {
  data () {
    // 验证教室格式
    var checkClassroom = (rule, value, cb) => {
      // 教的unicode码就是\u6559
      const regRoom = /^(\u6559)[\u4e09,\u56db,\u4e94]\d(0|1)\d/

      if (regRoom.test(value)) {
        return cb()
      }

      cb(new Error('请输入正确的教室名，样例格式：教三101'))
    }

    // 验证学分的格式
    var checkCredit = (rule, value, cb) => {
      // 教的unicode码就是\u6559
      const regRoom = /^\d\.(0|5)$/

      if (regRoom.test(value)) {
        return cb()
      }

      cb(new Error('请输入正确的学分格式, 样例格式：3.0'))
    }

    return {
      // 排课表单验证
      editLessonRules: {
        teacher_name: [
          { required: true, message: '请输入上课教师', trigger: 'change' }
        ],
        course_teacher_num: [
          { required: true, message: '请输入课程编号', trigger: 'blur' },
          { type: 'number', message: '请填写数字编号', trigger: 'blur' }
        ],
        class_name: [
          { required: true, message: '请输入上课专业', trigger: 'blur' }
        ],
        classroom: [
          { required: true, message: '请输入上课教室', trigger: 'blur' },
          { validator: checkClassroom, trigger: 'blur' }
        ],
        genre: [
          { required: true, message: '请选择课程分类', trigger: 'blur' }
        ],
        time_type: [
          { required: true, message: '请选择时间分类', trigger: 'blur' }
        ],
        class_period: [
          { required: true, message: '请输入实际课时', trigger: 'blur' },
          { type: 'number', message: '课时必须是数字', trigger: 'blur' }
        ],
        credict: [
          { required: true, message: '请输入实际学分', trigger: 'blur' },
          { validator: checkCredit, trigger: 'blur' }
        ],
        week_start: [
          { required: true, message: '请选择开始周次', trigger: 'blur' }
        ],
        week_end: [
          { required: true, message: '请选择结束周次', trigger: 'blur' }
        ]
      },

      // 课程列表数据
      lessonTable: [],
      // 搜索框部分
      searchValue: '',
      searchMethod: '1',
      // 删除弹框
      deleteDialogVisible: false,
      deleteLessonId: 0,
      // 当前课程记录
      currentLesson: {},
      // 安排课程抽屉部分
      editLessonDrawer: false,
      drawerDirection: 'rtl', // 代表从左到右RightToLeft
      currentPage: 1,
      totalLesson: 0,
      // 修改排课记录的数据表单
      editLessonForm: {},
      // 编辑排课记录的时间数组
      editTimeList: [{
        week: '',
        section: ''
      }],
      // 设定上课周期的选择值
      weekStart: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      weekEnd: [8, 9, 10, 11, 12, 13, 14, 15, 16],
      // 课程的状态
      course_status: 0,
      teacherList: [],
      majorList: []
    }
  },
  async created () {
    this.getLessonList()
    this.majorList = await getAllMajors()
    this.teacherList = await getAllTeachers()
  },
  methods: {
    // 搜索所有匹配到的课程
    async searchLesson () {
      this.getLessonList()
    },
    // 获取所有的排课记录
    async getLessonList () {
      // 以教师名查询
      if (this.searchMethod == 1) {
        // const { data: res } = await this.$http.post(`lesson/all/getLessonList?page=${this.currentPage - 1}&rows=10&lessonName=${this.searchValue}`)
        const { data: res } = await this.$http.post(`courseManagement/all/getCourseManagementList?page=${this.currentPage - 1}&rows=10&teacherName=` + this.searchValue)
        console.log(res)
        if (!res.state) return
        this.lessonTable = []
        this.foreachObj(res.detail)
        this.totalLesson = res.detail.total
        // console.log(this.lessonTable)
      }
      // 通过学院名搜索
      else if (this.searchMethod == 2) {
        const { data: res } = await this.$http.post(`courseManagement/all/getCourseManagementList?page=${this.currentPage - 1}&rows=10&courseName=` + this.searchValue)
        console.log(res)
        if (!res.state) return
        this.lessonTable = []
        this.foreachObj(res.detail)
        this.totalLesson = res.detail.total
      }
      // 按专业来查
      else if (this.searchMethod == 3) {
        const { data: res } = await this.$http.post(`courseManagement/all/getCourseManagementList?page=${this.currentPage - 1}&rows=10&className=` + this.searchValue)
        console.log(res)
        if (!res.state) return
        this.lessonTable = []
        this.foreachObj(res.detail)
        this.totalLesson = res.detail.total
      }
    },
    // 删除多个排课记录
    MultiLessonDelete () {
    },
    // 弹出删除框
    confirmDelete (id) {
      this.deleteDialogVisible = true
      this.deleteLessonId = id
    },
    // 删除单个排课
    async deleteLesson () {
      const { data: res } = await this.$http.post('courseManagement/admin/deleteCourseManagement?id=' + this.deleteLessonId)
      if (!res.state) return this.$message.error('删除失败！')
      this.$message.success('删除课程成功！')
      this.deleteDialogVisible = false
      this.getLessonList()
    },
    // 点击编辑，弹出编辑排课抽屉
    editLesson (lesson) {
      this.editLessonDrawer = true
      this.currentLesson = lesson
      // 将时间数据写入到editTimeList
      this.editTimeList = []
      lesson.time_list.forEach(item => {
        var time = {}
        time.week = item.courseTime.slice(0, 2)
        time.section = item.courseTime.slice(2)
        this.editTimeList.push(time)
      })
    },
    // 提交修改好的排课记录
    editLessonSubmit () {
      this.$refs.editLessonForm.validate(valid => {
        if (!valid) return
        const lesson = {
          id: '',
          classCycle: '',
          className: '',
          classPeriod: '',
          classroom: '',
          courseName: '',
          courseTeacherNum: 0,
          credict: '',
          genre: '',
          teacherName: ''
        }
        // 将所有的字段填到json数据中
        lesson.id = this.currentLesson.id
        // 首先上课周期是三个元素拼接到一起的，所以先处理
        lesson.classCycle = this.currentLesson.week_start + ' ' + this.currentLesson.week_end + ' ' + this.currentLesson.time_type
        // lesson.classCycle = this.currentLesson.class_cycle
        lesson.classPeriod = this.currentLesson.class_period
        lesson.classroom = this.currentLesson.classroom
        lesson.credict = this.currentLesson.credict
        lesson.genre = this.currentLesson.genre
        lesson.courseTeacherNum = this.currentLesson.course_teacher_num
        lesson.courseName = this.currentLesson.course_name
        lesson.teacherName = this.currentLesson.teacher_name
        lesson.className = this.currentLesson.class_name
        // 因为这里的课程一周里面可能会有多节课，
        // 所以我们应该设置一个section的list结构
        // 来传递courseTimeList
        var url = 'courseManagement/admin/updateCourseManagement?courseTimeList='
        this.editTimeList.forEach((item, index) => {
          url += item.week + item.section
          if (index != this.editTimeList.length - 1) {
            url += '&courseTimeList='
          }
        })
        this.$http({
          method: 'post',
          url: url,
          data: lesson
        }).then(res => {
          const data = res.data
          console.log(data)
          if (!data.state) return this.$message.error(data.msg)
          this.$message.success('修改记录成功！')
          this.editLessonDrawer = false
          this.getLessonList()
        })
      })
    },

    // 更改课程的状态
    async changeCourseStatus (id, status) {
      const { data: res } = await this.$http.post(`courseManagement/admin/updateCourseTeacherState?id=${id}&courseTeacherState=${status}`)
      console.log(res)
      if (!res.state) return this.$message.error(res.msg)
      // 更改状态之后不用刷新课程列表，因为按钮展示已经在课程中修改了
      return this.$message.success('修改状态成功!')
    },

    //
    /// / 增加一个时间及其所有值
    //
    // 向字典表单里面添加一个value值
    addTimeValues () {
      this.editTimeList.push({
        week: '',
        section: ''
      })
    },
    // 移除一个value值
    removeAddTime (value, index) {
      if (value.week !== undefined) {
        if (this.editTimeList.length > 1) {
          this.editTimeList.splice(index, 1)
        } else {
          this.editTimeList = [
            {
              week: '',
              section: ''
            }
          ]
        }
      }
    },
    // 更改页码，进行导航
    async handleCurrentChange (val) {
      // console.log(val)
      this.currentPage = val
      this.getLessonList()
    },
    handleClose (done) {
      done()
    },
    // 遍历所有的数据
    foreachObj (data) {
      data.list.forEach(item => {
        var obj = {
          id: 0,
          course_name: '',
          class_cycle: '',
          class_name: '',
          course_teacher_num: '',
          class_period: '',
          classroom: '',
          credict: '',
          genre: '',
          teacher_name: '',
          time_list: [],
          create_time: '',
          update_time: '',
          week_start: 0,
          week_end: 0,
          time_type: 0,
          course_teacher_state: 0
        }
        // 需要将classCycle拆分一下
        const cycle = item.class_cycle.split(' ')
        obj.week_start = cycle[0]
        obj.week_end = cycle[1]
        obj.time_type = cycle[2]

        obj.class_cycle = cycle[0] + '-' + cycle[1] + '周'
        obj.id = item.id
        obj.course_name = item.course_name
        obj.classroom = item.classroom
        obj.class_name = item.class_name
        obj.course_teacher_num = item.course_teacher_num
        obj.class_period = item.class_period
        obj.credict = item.credict
        obj.genre = item.genre
        obj.teacher_name = item.teacher_name
        obj.create_time = toDateString(item.create_time)
        obj.update_time = toDateString(item.update_time)
        obj.course_teacher_state = item.course_teacher_state
        this.$http.post(`courseManagement/all/selectCourseManagementListById?id=${item.id}`)
          .then(resp => {
            const { data: res } = resp
            // console.log(res)
            // 这里的解决方式暂时保留（有问题），
            // 后期需要存入多个时间点时就不能只取第一个时间了
            obj.time_list = res.detail.courseTime
          }).catch(err => {
            console.log(err)
          })
        this.lessonTable.push(obj)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.lesson-table {

  .el-dropdown-link {
    cursor: pointer;
    color: #27B148;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
}

.search-bar {
  margin-top: 20px;

  .el-select /deep/ .el-input {
    width: 110px;
  }
}

.lesson-list {
  margin-top: 20px;

  .el-table {

    .book-img {
      height: 100px;
    }
  }

  .el-pagination {
    margin: 12px 0;
    float: right;
  }
}

.add-lesson {
  font-size: 14px;

  .el-row {
    margin-left: 10px !important;
    margin-bottom: 20px;

    i {
      color: red;
    }

    .el-input {
      width: 200px;
    }
  }

  .el-button.submit {
    margin-left: 120px;
  }
}

.setlessontitle {
  padding: 20px;
  padding-top: 0px;
  color: rgb(137, 144, 145);
}
</style>
